/**
 * @swagger
 * /api/asset/basic-stats:
 *   get:
 *     tags:
 *       - 资产管理
 *     summary: 获取资产基础统计数据
 *     description: 获取资产的基本统计信息，包括总数量、总价值、分类统计等，支持时间筛选
 *     parameters:
 *       - in: query
 *         name: startDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始日期 (YYYY-MM-DD)
 *         example: "2023-01-01"
 *       - in: query
 *         name: endDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束日期 (YYYY-MM-DD)
 *         example: "2023-12-31"
 *     responses:
 *       200:
 *         description: 成功获取基础统计数据
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                   description: 响应状态码
 *                 message:
 *                   type: string
 *                   example: "基础统计获取成功"
 *                   description: 响应消息
 *                 data:
 *                   type: object
 *                   properties:
 *                     overview:
 *                       type: object
 *                       properties:
 *                         totalAssets:
 *                           type: integer
 *                           description: 资产总数
 *                           example: 1250
 *                         totalValue:
 *                           type: string
 *                           description: 资产总价值
 *                           example: "15680000.50"
 *                         totalFiscalFunding:
 *                           type: string
 *                           description: 财政拨款总额
 *                           example: "12500000.00"
 *                         totalBuildingArea:
 *                           type: string
 *                           description: 建筑面积总和
 *                           example: "125000.50"
 *                         totalLandArea:
 *                           type: string
 *                           description: 土地面积总和
 *                           example: "250000.75"
 *                         totalKeepers:
 *                           type: integer
 *                           description: 保管员总数
 *                           example: 45
 *                         totalGGJCategories:
 *                           type: integer
 *                           description: 固定资产分类总数
 *                           example: 12
 *                         totalGB22Categories:
 *                           type: integer
 *                           description: 国标分类总数
 *                           example: 8
 *                     pricing:
 *                       type: object
 *                       properties:
 *                         minPrice:
 *                           type: string
 *                           description: 最低价格
 *                           example: "500.00"
 *                         maxPrice:
 *                           type: string
 *                           description: 最高价格
 *                           example: "2500000.00"
 *                         assetsWithPrice:
 *                           type: integer
 *                           description: 有价格的资产数量
 *                           example: 1180
 *                         assetsWithoutPrice:
 *                           type: integer
 *                           description: 无价格的资产数量
 *                           example: 70
 *                     areas:
 *                       type: object
 *                       properties:
 *                         averageLandArea:
 *                           type: string
 *                           description: 平均土地面积
 *                           example: "1250.75"
 *                         buildingAreaCount:
 *                           type: integer
 *                           description: 有建筑面积的资产数量
 *                           example: 850
 *                         landAreaCount:
 *                           type: integer
 *                           description: 有土地面积的资产数量
 *                           example: 200
 *                     fiscal:
 *                       type: object
 *                       properties:
 *                         fiscalFundedAssets:
 *                           type: integer
 *                           description: 财政拨款资产数量
 *                           example: 980
 *                         nonFiscalAssets:
 *                           type: integer
 *                           description: 非财政拨款资产数量
 *                           example: 270
 *                         fiscalFundingRatio:
 *                           type: string
 *                           description: 财政拨款比例
 *                           example: "78.40"
 *                     averages:
 *                       type: object
 *                       properties:
 *                         averagePrice:
 *                           type: string
 *                           description: 平均价格
 *                           example: "12544.00"
 *                         averageBuildingArea:
 *                           type: string
 *                           description: 平均建筑面积
 *                           example: "100.00"
 *                         averageFiscalFunding:
 *                           type: string
 *                           description: 平均财政拨款
 *                           example: "10000.00"
 *                         assetsPerKeeper:
 *                           type: string
 *                           description: 每个保管员平均资产数
 *                           example: "27.78"
 *       500:
 *         description: 服务器内部错误
 */
import { withCors } from '../../../lib/cors';
import { success, error as errorResponse, handleResponse } from '../../../lib/response';
import { query } from '../../../lib/db';

/**
 * 处理资产基础统计请求
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function handler(req, res) {
  try {
    const { startDate, endDate } = req.query;

    let whereClause = '';
    const params = [];

    if (startDate && endDate) {
      whereClause = 'WHERE PURCHASE_DATE BETWEEN ? AND ?';
      params.push(startDate, endDate);
    } else if (startDate) {
      whereClause = 'WHERE PURCHASE_DATE >= ?';
      params.push(startDate);
    } else if (endDate) {
      whereClause = 'WHERE PURCHASE_DATE <= ?';
      params.push(endDate);
    }
    
        // 基础统计查询
    const basicQuery = `
      SELECT 
        COUNT(*) as totalAssets,
        SUM(COALESCE(STOCK_PRICE, 0)) as totalValue,
        SUM(COALESCE(CAIZXJFLY, 0)) as totalFiscalFunding,
        SUM(COALESCE(CHEKMJ, 0)) as totalBuildingArea,
        SUM(COALESCE(FENTMJ, 0)) as totalLandArea,
        AVG(COALESCE(STOCK_PRICE, 0)) as avgPrice,
        COUNT(DISTINCT BASE_TEACHER_NAME_KEEPER) as totalKeepers,
        COUNT(DISTINCT ASSETS_SORT_GGJ_NAME) as totalGGJCategories,
        COUNT(DISTINCT ASSETS_SORT_GB22_NAME) as totalGB22Categories
      FROM wd_sec_assets12
      ${whereClause}
    `;

    const basicResult = await query(basicQuery, params);
    const data = basicResult[0];

    // 价格分布统计
    const priceStatsQuery = `
      SELECT 
        MIN(STOCK_PRICE) as minPrice,
        MAX(STOCK_PRICE) as maxPrice,
        COUNT(CASE WHEN STOCK_PRICE > 0 THEN 1 END) as assetsWithPrice,
        COUNT(CASE WHEN STOCK_PRICE IS NULL OR STOCK_PRICE = 0 THEN 1 END) as assetsWithoutPrice
      FROM wd_sec_assets12
      ${whereClause}
    `;

    const priceResult = await query(priceStatsQuery, params);
    const priceStats = priceResult[0];

    // 面积统计
    const areaStatsQuery = `
      SELECT 
        COUNT(CASE WHEN CHEKMJ > 0 THEN 1 END) as buildingAreaCount,
        COUNT(CASE WHEN FENTMJ > 0 THEN 1 END) as landAreaCount,
        AVG(COALESCE(CHEKMJ, 0)) as avgBuildingArea,
        AVG(COALESCE(FENTMJ, 0)) as avgLandArea
      FROM wd_sec_assets12
      ${whereClause}
    `;

    const areaResult = await query(areaStatsQuery, params);
    const areaStats = areaResult[0];

    // 财政拨款统计
    const fiscalStatsQuery = `
      SELECT 
        COUNT(CASE WHEN CAIZXJFLY > 0 THEN 1 END) as fiscalFundedAssets,
        COUNT(CASE WHEN CAIZXJFLY IS NULL OR CAIZXJFLY = 0 THEN 1 END) as nonFiscalAssets,
        AVG(COALESCE(CAIZXJFLY, 0)) as avgFiscalFunding,
        SUM(COALESCE(CAIZXJFLY, 0)) / SUM(COALESCE(STOCK_PRICE, 1)) * 100 as fiscalFundingRatio
      FROM wd_sec_assets12
      ${whereClause}
    `;

    const fiscalResult = await query(fiscalStatsQuery, params);
    const fiscalStats = fiscalResult[0];

    const responseData = {
      overview: {
        totalAssets: parseInt(data.totalAssets),
        totalValue: parseFloat(data.totalValue || 0).toFixed(2),
        totalFiscalFunding: parseFloat(data.totalFiscalFunding || 0).toFixed(2),
        totalBuildingArea: parseFloat(data.totalBuildingArea || 0).toFixed(2),
        totalLandArea: parseFloat(data.totalLandArea || 0).toFixed(2),
        totalKeepers: parseInt(data.totalKeepers),
        totalGGJCategories: parseInt(data.totalGGJCategories),
        totalGB22Categories: parseInt(data.totalGB22Categories)
      },
      pricing: {
        minPrice: parseFloat(priceStats.minPrice || 0).toFixed(2),
        maxPrice: parseFloat(priceStats.maxPrice || 0).toFixed(2),
        assetsWithPrice: parseInt(priceStats.assetsWithPrice),
        assetsWithoutPrice: parseInt(priceStats.assetsWithoutPrice)
      },
      areas: {
        averageLandArea: parseFloat(areaStats.avgLandArea || 0).toFixed(2),
        buildingAreaCount: parseInt(areaStats.buildingAreaCount),
        landAreaCount: parseInt(areaStats.landAreaCount)
      },
      fiscal: {
        fiscalFundedAssets: parseInt(fiscalStats.fiscalFundedAssets),
        nonFiscalAssets: parseInt(fiscalStats.nonFiscalAssets),
        fiscalFundingRatio: parseFloat(fiscalStats.fiscalFundingRatio || 0).toFixed(2)
      },
      averages: {
        averagePrice: (parseFloat(data.totalValue || 0) / parseInt(data.totalAssets || 1)).toFixed(2),
        averageBuildingArea: (parseFloat(data.totalBuildingArea || 0) / parseInt(data.totalAssets || 1)).toFixed(2),
        averageFiscalFunding: (parseFloat(data.totalFiscalFunding || 0) / parseInt(data.totalAssets || 1)).toFixed(2),
        assetsPerKeeper: (parseInt(data.totalAssets || 0) / parseInt(data.totalKeepers || 1)).toFixed(2)
      }
    };

    return handleResponse(res, success(responseData, "资产基础统计获取成功"));
    
  } catch (error) {
    console.error('Asset basic stats error:', error);
    return handleResponse(res, errorResponse("获取资产基础统计失败", 500));
  }
}

export default withCors(handler, ['GET']);